<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/app/service/Curl.php'; // 引入Curl.php文件
require_once __DIR__ . '/app/service/Rsa.php'; // 引入Rsa.php文件
require_once __DIR__ . '/app/service/Aes.php'; // 引入Aes.php文件

use App\Service\Rsa;
use App\Service\Aes;

define("ROOT", __DIR__);

// 从文件加载公钥
$publicKey = Rsa::loadKey('rsa', 'public');
// 加载私钥
$privateKey = Rsa::loadKey('rsa', 'private');



// 准备要加密的消息
$messageData = json_encode(['trade_msg' => "Hello, Workerman!"]);
// 使用AES加密消息
$encryptedMessage = Aes::encrypt($messageData);
//var_dump($encryptedMessage);
//exit();
echo "AES Data (Base64): " . $encryptedMessage['data'] . "\n";
echo "AES Key: " . $encryptedMessage['key'] . "\n";
echo "AES IV: " . $encryptedMessage['iv'] . "\n";

// 准备要签名的数据
$signData = json_encode(['session_id' => 'c3656bdf-cd66-426c-8bb5-ea08493b316f', 'phone' => '13718270287', 'time' => time(),'iv'=>$encryptedMessage['iv']]);
// 使用公钥加密签名数据
$encryptedSign = Rsa::encryptData($signData, $publicKey);
echo "Header Encrypted (Base64): " . $encryptedSign . "\n";
// 使用公钥加密AES密钥
$encryptedMessage['key'] = Rsa::encryptData($encryptedMessage['key'], $publicKey);

// 准备发送的body内容
$body = json_encode($encryptedMessage);
echo "Body:\n" . $body . "\n";
echo '------------------------------' . "\n";
// 使用私钥解密签名数据
$decryptedHeader = Rsa::decryptData($encryptedSign, $privateKey);
echo "Decrypted Header Data: " . $decryptedHeader . "\n";
$headerArr=json_decode($decryptedHeader, true);
var_dump($headerArr);


// 解析body内容
$jsonOb = json_decode($body, true);
//var_dump($jsonOb);
//exit();
// 使用私钥解密AES密钥
$decryptedAesKey = Rsa::decryptData($jsonOb['key'], $privateKey);
echo "Decrypted AES Key: " . $decryptedAesKey . "\n";

// 使用解密后的AES密钥解密数据
$decryptedData = Aes::decrypt($jsonOb['data'], $decryptedAesKey,$headerArr['iv']);
echo "Decrypted Data: " . $decryptedData . "\n";


